<template>
  <div class="add-agent" v-loading="loading">
    <el-form ref="form" :model="formData" label-width="80px">
      <el-form-item label="账号" required>
        <el-input v-model="formData.username" @blur="blurUsername" placeholder="请输入账户(用户名)"></el-input>
      </el-form-item>
      <el-form-item label="账号密码" required>
        <el-input v-model="formData.password_raw" @blur="blurPassword" placeholder="请输入账号密码"></el-input>
      </el-form-item>
      <el-form-item label="代理人" required>
        <el-input v-model="formData.name" placeholder="请输入代理人名称"></el-input>
      </el-form-item>
    </el-form>
    <el-tabs v-model="activeArea" tab-position="left" @tab-click="handleClick">
      <el-tab-pane v-for="(item) in state.areaList" :key="item.id" :label="item.name" :name="item.id">
        <div class="add-agent-checkox" v-loading="loading">
          <el-input clearable placeholder="请输入要搜索的学校名称" v-model="item.schoolName" class="input-with-select">
            <template #append>
              <el-button class="input-with-button" @click="searchSchool(activeArea,item.schoolName)">搜索</el-button>
            </template>
          </el-input>
          <div v-if="item.collegeList.length > 0">
            <el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checkAll" @change="checked=>handleCheckAllChange(checked, item.id)">全选</el-checkbox>
            <el-checkbox-group v-model="item.checkboxGroup" @change="list=>handleCheckedSchoolChange(list, item.id)">
              <div v-for="item in item.collegeList" :key="item.id">
                <el-checkbox :value="item.id" :label="item.id">{{item.name_zh}}—{{item.name}}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
          <el-empty v-else :image-size="80"></el-empty>
        </div>
        <!-- <div>
          <div v-if="activeArea == 1" class="add-agent-checkox"  v-loading="loading">
            <el-input clearable placeholder="请输入要搜索的学校名称" v-model="schoolName1" class="input-with-select">
              <template #append>
                <el-button class="input-with-button" @click="searchSchool(activeArea,schoolName1)">搜索</el-button>
              </template>
            </el-input>
            <div v-if="state.collegeList1.length > 0">
              <el-checkbox-group v-model="state.checkboxGroup1">
                <div v-for="item in state.collegeList1" :key="item.id">
                  <el-checkbox :value="item.id" :label="item.id">{{item.name_zh}}—{{item.name}}</el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
            <el-empty v-else :image-size="80"></el-empty>
          </div>
          <div v-if="activeArea == 2" class="add-agent-checkox" v-loading="loading">
            <el-input clearable placeholder="请输入要搜索的学校名称" v-model="schoolName2" class="input-with-select">
              <template #append>
                <el-button class="input-with-button" @click="searchSchool(activeArea,schoolName2)">搜索</el-button>
              </template>
            </el-input>
            <div v-if="state.collegeList2.length > 0">
            <el-checkbox-group v-model="state.checkboxGroup2">
              <div v-for="item in state.collegeList2" :key="item.id">
                <el-checkbox :value="item.id" :label="item.id">{{item.name_zh}}—{{item.name}}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
          <el-empty v-else :image-size="80"></el-empty>
          </div>
          <div v-if="activeArea == 3" class="add-agent-checkox" v-loading="loading">
            <el-input clearable placeholder="请输入要搜索的学校名称" v-model="schoolName3" class="input-with-select">
              <template #append>
                <el-button class="input-with-button" @click="searchSchool(activeArea,schoolName3)">搜索</el-button>
              </template>
            </el-input>
            <div v-if="state.collegeList3.length > 0">
              <el-checkbox-group v-model="state.checkboxGroup3">
                <div v-for="item in state.collegeList3" :key="item.id">
                  <el-checkbox :value="item.id" :label="item.id">{{item.name_zh}}—{{item.name}}</el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
            <el-empty v-else :image-size="80"></el-empty>
          </div>
          <div v-if="activeArea == 4" class="add-agent-checkox" v-loading="loading">
            <el-input clearable placeholder="请输入要搜索的学校名称" v-model="schoolName4" class="input-with-select">
              <template #append>
                <el-button class="input-with-button" @click="searchSchool(activeArea,schoolName4)">搜索</el-button>
              </template>
            </el-input>
            <div v-if="state.collegeList4.length > 0">
                <el-checkbox-group v-model="state.checkboxGroup4">
                  <div v-for="item in state.collegeList4" :key="item.id">
                    <el-checkbox :value="item.id" :label="item.id">{{item.name_zh}}—{{item.name}}</el-checkbox>
                  </div>
                </el-checkbox-group>
            </div>
            <el-empty v-else :image-size="80"></el-empty>
          </div>
          <div v-if="activeArea == 5" class="add-agent-checkox" v-loading="loading">
            <el-input clearable placeholder="请输入要搜索的学校名称" v-model="schoolName5" class="input-with-select">
              <template #append>
                <el-button class="input-with-button" @click="searchSchool(activeArea,schoolName5)">搜索</el-button>
              </template>
            </el-input>
            <div v-if="state.collegeList5.length > 0">
              <el-checkbox-group v-model="state.checkboxGroup5">
                  <div v-for="item in state.collegeList5" :key="item.id">
                    <el-checkbox :value="item.id" :label="item.id">{{item.name_zh}}—{{item.name}}</el-checkbox>
                  </div>
              </el-checkbox-group>
            </div>
            <el-empty v-else :image-size="80"></el-empty>
          </div>
          <div v-if="activeArea == 6" class="add-agent-checkox" v-loading="loading">
            <el-input clearable placeholder="请输入要搜索的学校名称" v-model="schoolName6" class="input-with-select">
              <template #append>
                <el-button class="input-with-button" @click="searchSchool(activeArea,schoolName6)">搜索</el-button>
              </template>
            </el-input>
            <div v-if="state.collegeList6.length > 0">
              <el-checkbox-group v-model="state.checkboxGroup6">
                <div v-for="item in state.collegeList6" :key="item.id">
                  <el-checkbox :value="item.id" :label="item.id">{{item.name_zh}}—{{item.name}}</el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
            <el-empty v-else :image-size="80"></el-empty>
          </div>
          <div v-if="activeArea == 7" class="add-agent-checkox" v-loading="loading">
            <el-input clearable placeholder="请输入要搜索的学校名称" v-model="schoolName7" class="input-with-select">
              <template #append>
                <el-button class="input-with-button" @click="searchSchool(activeArea,schoolName7)">搜索</el-button>
              </template>
            </el-input>
            <div v-if="state.collegeList7.length > 0">
              <el-checkbox-group v-model="state.checkboxGroup7">
                <div v-for="item in state.collegeList7" :key="item.id">
                  <el-checkbox :value="item.id" :label="item.id">{{item.name_zh}}—{{item.name}}</el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
            <el-empty v-else :image-size="80"></el-empty>
          </div>
        </div> -->
      </el-tab-pane>
    </el-tabs>
    <div class="add-agent-submit">
      <el-button @click="onSubmit(0)">取消</el-button>
      <el-button type="primary" @click="onSubmit(1)">确认</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref,reactive,computed,onMounted} from 'vue';
import { ElMessage ,} from 'element-plus';
import API from "@/utils/api";
import { defineProps, defineEmits } from 'vue';
const emits = defineEmits(['closeAgent']);
const props = defineProps({
  parmas: Object,
});
const loading = ref(false)
const activeArea = ref(1)
let formData = reactive({
  username:'',
  password_raw:'',
  name:'',
  colleges:[],
})
let formDataClone = reactive({
  usernameClone:'',
  passwordRawClone:'',
})
function blurUsername() {
  if(props.parmas.type === 'update') {
    if(formDataClone.usernameClone !== formData.username) {
      ElMessage.warning('您更改了代理的用户名,这会导致代理无法登陆,请谨慎操作!')
    }
  }
}
function blurPassword() {
  if(props.parmas.type === 'update') {
    if(formDataClone.passwordRawClone !== formData.password_raw) {
      ElMessage.warning('您更改了代理的密码,这会导致代理无法登陆,请谨慎操作!')
    }
  }
}
const id = ref('')
const state = reactive({
  areaList:[],
})
// 选择地区获取学校数据
function handleClick(tab) {
  // console.log(tab,'tab');
  // schoolName.value = ''
  // if(props.parmas.type === 'add') {
  //   id.value = 0
  // }else {
  //   id.value = props.parmas.rowInfo.id
  // }
}
function getCheckedStatus (list,val) {
  let checkedCount = list.length
  state.areaList.forEach((item,index) => {
    if(val === item.id) {
      item.checkAll = checkedCount === item.collegeList.length
      if(checkedCount >= 0 && checkedCount < item.collegeList.length) {
        item.isIndeterminate = true
      }else {
        item.isIndeterminate = false
      }
    }
  })
}
// 获取默认的地区学校数据
function getDefaultCollegeList (val) {
  loading.value = true
  API.agentList.getCollegeList({id:val,areas_id:1,}, (res) => {
    if(res.code == 0) {
      loading.value = false
      state.areaList[0].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[0].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[0].checkboxGroup,1)
          }
        });
      }
    }
  })
}
function getCollegeList2 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:2,}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[1].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[1].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[1].checkboxGroup,2)
          }
        });
      }
    }
  })
}
function getCollegeList3 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:3,}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[2].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[2].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[2].checkboxGroup,3)
          }
        });
      }
    }
  })
}
function getCollegeList4 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:4}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[3].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[3].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[3].checkboxGroup,4)
          }
        });
      }
    }
  })
}
function getCollegeList5 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:5}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[4].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[4].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[4].checkboxGroup,5)
          }
        });
      }
    }
  })
}
function getCollegeList6 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:6}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[5].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[5].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[5].checkboxGroup,6)
          }
        });
      }
    }
  })
}
function getCollegeList7 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:7}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[6].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[6].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[6].checkboxGroup,7)
          }
        });
      }
    }
  })
}
function getCollegeList8 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:8}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[7].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[7].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[7].checkboxGroup,8)
          }
        });
      }
    }
  })
}
function getCollegeList9 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:9}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[8].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[8].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[8].checkboxGroup,9)
          }
        });
      }
    }
  })
}
function getCollegeList10 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:10}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[9].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[9].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[9].checkboxGroup,10)
          }
        });
      }
    }
  })
}
function getCollegeList11 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:11}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[10].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[10].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[10].checkboxGroup,11)
          }
        });
      }
    }
  })
}
function getCollegeList12 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:12}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[11].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[11].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[11].checkboxGroup,12)
          }
        });
      }
    }
  })
}
function getCollegeList13 (id,paneName) {
  loading.value = true
  API.agentList.getCollegeList({id:id,areas_id:13}, (res) => {
    loading.value = false
    if(res.code === 0) {
      state.areaList[12].collegeList = res.data
      if(res.data.length > 0) {
        res.data.forEach(item => {
          if(item.checked === 1) {
            state.areaList[12].checkboxGroup.push(item.id)
            getCheckedStatus (state.areaList[12].checkboxGroup,13)
          }
        });
      }
    }
  })
}
// 搜索学校
function searchSchool(paneName,schoolName) {
  if(props.parmas.type === 'add') {
    id.value = 0
  }else {
    id.value = props.parmas.rowInfo.id
  }
  API.agentList.getCollegeList({id:id.value,areas_id:paneName,name:schoolName}, (res) => {
    if(res.code === 0) {
      state.areaList[paneName-1].collegeList = res.data
    }
  })
}
// 获取地区数据
function getAreaList () {
  return new Promise(function(resolve,reject){
    loading.value = true
    API.schoolList.getAreaList({}, (res) => {
      loading.value = false
      if(res.code == 0) {
        res.data.forEach((item) => {
          item.checkboxGroup = []
          item.collegeList = []
          item.schoolName = null
          item.isIndeterminate = false
          item.checkAll = false
        })
        state.areaList = res.data
        resolve()
      }
    })
  })
}
// 全选
function handleCheckAllChange(checked, val) {
  state.areaList.forEach((item,index) => {
    if(val === item.id) {
      item.isIndeterminate = false
      item.checkboxGroup = []
      if(checked) {
        item.collegeList.forEach((item1,index1) => {
          item.checkboxGroup.push(item1.id)
        })
      }
    }
  })
}
// 单选
function handleCheckedSchoolChange (list, val) {
  let checkedCount = list.length
  state.areaList.forEach((item,index) => {
    if(val === item.id) {
      item.checkAll = checkedCount === item.collegeList.length
      item.isIndeterminate = checkedCount > 0 && checkedCount < item.collegeList.length
    }
  })
}
// 正则检验
function containsChineseCharacters(password) {
  // 使用正则表达式检查密码是否包含中文字符
  return /[\u4E00-\u9FFF]/.test(password);
}
// 提交数据
function onSubmit(type) {
  if(type === 0) {
    return emits('closeAgent',type)
  }
  let checkList = []
  state.areaList.forEach((item,index) => {
    if(item.checkboxGroup.length > 0) {
      item.checkboxGroup.forEach(item_ => {
        checkList.push(item_)
      })
    }
  })
  formData.colleges = checkList
  let message = !formData.username && '请输入账号(用户名)' ||
                !formData.password_raw && '请输入账号密码' ||
                formData.password_raw.length < 6 && '账号密码必须大于5位' ||
                containsChineseCharacters(formData.password_raw) && '账号密码中不能包含中文字符！' ||
                !formData.name && '请输入代理人名称' || null;
                // formData.colleges.length < 1 && '请选中代理人所代理的学校' || null;
  if(message) return ElMessage.warning(message)
  if(props.parmas.type === 'add') {  // 新增
    API.agentList.addAgent({...formData},(res) => {
      if(res.code == 0) {
        emits('closeAgent',type)
        ElMessage.success('新增成功')
      }
    })
  }else {   //修改
    API.agentList.editAgent({...formData,id:props.parmas.rowInfo.id},(res) => {
      if(res.code == 0) {
        emits('closeAgent',type)
        ElMessage.success('修改成功')
      }
    })
  }
}
function generateAccount() {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
  const account = 'agent' + year + month + Math.floor(Math.random() * 10000);
  formData.username = account;
}
function generatePassword() {
  const password = Math.random().toString(36).slice(2, 8); 
  formData.password_raw = password;
}
onMounted(async() => {
  if(props.parmas.type === 'update') {
    formData = reactive({
      username:props.parmas.rowInfo.username,
      password_raw:props.parmas.rowInfo.password_raw,
      name:props.parmas.rowInfo.name,
      colleges:[],
    })
    formDataClone = reactive({
      usernameClone:props.parmas.rowInfo.username,
      passwordRawClone:props.parmas.rowInfo.password_raw,
    })
  }
  await getAreaList()
  if(props.parmas.type === 'add') {
    generateAccount()
    generatePassword()
    id.value = 0
  }else {
    id.value = props.parmas.rowInfo.id
  }
  getDefaultCollegeList(id.value)
  getCollegeList2(id.value)
  getCollegeList3(id.value)
  getCollegeList4(id.value)
  getCollegeList5(id.value)
  getCollegeList6(id.value)
  getCollegeList7(id.value)
  getCollegeList8(id.value)
  getCollegeList9(id.value)
  getCollegeList10(id.value)
  getCollegeList11(id.value)
  getCollegeList12(id.value)
  getCollegeList13(id.value)
})
</script>

<style lang="scss" scoped>
.add-agent {
  .input-with-button {
    color: #fff;
    background: #409eff;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
  .el-input-group {
    width:70%
  } 
  .add-agent-submit {
    margin-top: 30px;
  }
  .add-agent-checkox {
    max-height: 250px;
    overflow: auto;
    text-align: start;
    padding: 10px;
  }
}
</style>